package com.cloud.mall.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cloud.mall.api.CommonPage;
import com.cloud.mall.base.BaseResponse;
import com.cloud.mall.core.bean.MallBeanUtils;
import com.cloud.mall.ums.mapper.UmsAdminLoginLogMapper;
import com.cloud.mall.ums.mapper.UmsAdminMapper;
import com.cloud.mall.ums.mapper.UmsAdminPermissionRelationMapper;
import com.cloud.mall.ums.mapper.UmsAdminRoleRelationMapper;
import com.cloud.mall.ums.model.*;
import com.cloud.mall.user.dao.UmsAdminPermissionRelationDao;
import com.cloud.mall.user.dao.UmsAdminRoleRelationDao;
import com.cloud.mall.user.dto.UpdateAdminPasswordParam;
import com.cloud.mall.user.input.UmsAdminInpDTO;
import com.cloud.mall.user.output.UmsAdminOut;
import com.cloud.mall.user.output.UmsMenuOut;
import com.cloud.mall.user.output.UmsPermissionOut;
import com.cloud.mall.user.output.UmsRoleOut;
import com.cloud.mall.usr.service.UmsAdminService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class UmsAdminServiceImpl  implements UmsAdminService {

    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UmsAdminRoleRelationMapper adminRoleRelationMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;
    @Autowired
    private UmsAdminPermissionRelationMapper adminPermissionRelationMapper;
    @Autowired
    private UmsAdminPermissionRelationDao adminPermissionRelationDao;
    @Autowired
    private UmsAdminLoginLogMapper loginLogMapper;

    @Override
    public BaseResponse<UmsAdminOut> getItem(Long id) {
        UmsAdmin umsAdmin= adminMapper.selectByPrimaryKey(id);
        return BaseResponse.setResultSuccess(MallBeanUtils.doToDto(umsAdmin, UmsAdminOut.class));
    }

    @Override
    public BaseResponse<UmsAdminOut> register(@RequestBody UmsAdminInpDTO umsAdminInpDTO) {
        UmsAdmin umsAdmin = new UmsAdmin();
        BeanUtils.copyProperties(umsAdminInpDTO, umsAdmin);
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setStatus(1);
        //查询是否有相同用户名的用户
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
        List<UmsAdmin> umsAdminList = adminMapper.selectByExample(example);
        if (umsAdminList.size() > 0) {
            return BaseResponse.setResultError("用户已存在");
        }
        //将密码进行加密操作
        // String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());
        umsAdmin.setPassword("");
        adminMapper.insert(umsAdmin);
        return BaseResponse.setResultSuccess(MallBeanUtils.doToDto(umsAdmin, UmsAdminOut.class));
    }

    @Override
    public BaseResponse<CommonPage<UmsAdminOut>> list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        UmsAdminExample example = new UmsAdminExample();
        UmsAdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andUsernameLike("%" + keyword + "%");
            example.or(example.createCriteria().andNickNameLike("%" + keyword + "%"));
        }
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        List<UmsAdminOut> adminOuts=MallBeanUtils.copyDoToDto(adminList,UmsAdminOut.class);
        return BaseResponse.setResultSuccess(CommonPage.restPage(adminOuts));
    }

    @Override
    public BaseResponse update(Long id, UmsAdminInpDTO adminInpDTO) {
        UmsAdmin admin = MallBeanUtils.dtoToDo(adminInpDTO,UmsAdmin.class);
        admin.setId(id);
        UmsAdmin rawAdmin = adminMapper.selectByPrimaryKey(id);
        if(rawAdmin.getPassword().equals(admin.getPassword())){
            //与原加密密码相同的不需要修改
            admin.setPassword(null);
        }else{
            //与原加密密码不同的需要加密修改
            if(StrUtil.isEmpty(admin.getPassword())){
                admin.setPassword(null);
            }else{
                admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            }
        }
        int count= adminMapper.updateByPrimaryKeySelective(admin);
        if(count==0){
            return  BaseResponse.setResultError();
        }
        return BaseResponse.setResultSuccess();
    }

    @Override
    public BaseResponse delete(Long id) {
        int count= adminMapper.deleteByPrimaryKey(id);
        if(count==0){
            return  BaseResponse.setResultError();
        }
        return BaseResponse.setResultSuccess();
    }

    @Transactional
    @Override
    public BaseResponse updateRole(Long adminId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        UmsAdminRoleRelationExample adminRoleRelationExample = new UmsAdminRoleRelationExample();
        adminRoleRelationExample.createCriteria().andAdminIdEqualTo(adminId);
        adminRoleRelationMapper.deleteByExample(adminRoleRelationExample);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<UmsAdminRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            count=adminRoleRelationDao.insertList(list);
        }
            if(count==0){
                return  BaseResponse.setResultError();
            }
            return BaseResponse.setResultSuccess();

    }

    @Transactional
    @Override
    public BaseResponse updatePassword(UpdateAdminPasswordParam param) {
        if(StrUtil.isEmpty(param.getUsername())
                ||StrUtil.isEmpty(param.getOldPassword())
                ||StrUtil.isEmpty(param.getNewPassword())){
            return BaseResponse.setResultError("提交参数不合法");
        }
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(param.getUsername());
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        if(CollUtil.isEmpty(adminList)){
            return BaseResponse.setResultError("找不到该用户");
        }
        UmsAdmin umsAdmin = adminList.get(0);
        if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){
            return BaseResponse.setResultError("旧密码错误");
        }
        umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
        int status = adminMapper.updateByPrimaryKey(umsAdmin);
            return  BaseResponse.setResultSuccess(status);
    }

    @Override
    public BaseResponse updateStatus(Long id, Integer status) {
        UmsAdminInpDTO umsAdmin = new UmsAdminInpDTO();
        umsAdmin.setStatus(status);
       return update(id,umsAdmin);
    }

    @Override
    public BaseResponse<List<UmsRoleOut>> getRoleList(Long adminId) {
        List<UmsRole> roleList = adminRoleRelationDao.getRoleList(adminId);
        return  BaseResponse.setResultSuccess(MallBeanUtils.copyDoToDto(roleList,UmsRoleOut.class));
    }

    @Transactional
    @Override
    public BaseResponse updatePermission(Long adminId, List<Long> permissionIds) {
        //删除原所有权限关系
        UmsAdminPermissionRelationExample relationExample = new UmsAdminPermissionRelationExample();
        relationExample.createCriteria().andAdminIdEqualTo(adminId);
        adminPermissionRelationMapper.deleteByExample(relationExample);
        //获取用户所有角色权限
        List<UmsPermission> permissionList = adminRoleRelationDao.getRolePermissionList(adminId);
        List<Long> rolePermissionList = permissionList.stream().map(UmsPermission::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(permissionIds)) {
            List<UmsAdminPermissionRelation> relationList = new ArrayList<>();
            //筛选出+权限
            List<Long> addPermissionIdList = permissionIds.stream().filter(permissionId -> !rolePermissionList.contains(permissionId)).collect(Collectors.toList());
            //筛选出-权限
            List<Long> subPermissionIdList = rolePermissionList.stream().filter(permissionId -> !permissionIds.contains(permissionId)).collect(Collectors.toList());
            //插入+-权限关系
            relationList.addAll(convert(adminId,1,addPermissionIdList));
            relationList.addAll(convert(adminId,-1,subPermissionIdList));
            int count= adminPermissionRelationDao.insertList(relationList);
            if(count==0){
                return  BaseResponse.setResultError();
            }
            return BaseResponse.setResultSuccess();
        }
        return null;
    }

    @Override
    public BaseResponse<List<UmsPermissionOut>> getPermissionList(Long adminId) {
        List<UmsPermission> permissionList = adminRoleRelationDao.getPermissionList(adminId);
        return  BaseResponse.setResultSuccess(MallBeanUtils.copyDoToDto(permissionList,UmsPermissionOut.class));
    }

    /**
     * 将+-权限关系转化为对象
     */
    private List<UmsAdminPermissionRelation> convert(Long adminId,Integer type,List<Long> permissionIdList) {
        List<UmsAdminPermissionRelation> relationList = permissionIdList.stream().map(permissionId -> {
            UmsAdminPermissionRelation relation = new UmsAdminPermissionRelation();
            relation.setAdminId(adminId);
            relation.setType(type);
            relation.setPermissionId(permissionId);
            return relation;
        }).collect(Collectors.toList());
        return relationList;
    }
}
